import { Ref, SetupContext, computed, nextTick, ref } from "vue";
import { ButtonEditProps } from "../button-edit.props";
import { UsePopup } from "./types";

export function usePopup(
    props: ButtonEditProps,
    context: SetupContext,
    buttonEditRef: Ref<any>,
): UsePopup {
    const popoverRef = ref<any>();
    const shouldPopupContent = ref(false);

    function tryShowPopover() {
        const popoverInstance = popoverRef.value;
        if (popoverInstance) {
            popoverInstance.show(buttonEditRef.value);
        }
    }

    async function togglePopup() {
        const hasContent = !!context.slots.default;
        if (hasContent) {
            shouldPopupContent.value = !shouldPopupContent.value;
            await nextTick();
            tryShowPopover();
        }
    }

    async function popup() {
        const hasContent = !!context.slots.default;
        if (hasContent) {
            shouldPopupContent.value = true;
            await nextTick();
            tryShowPopover();
        }
    }

    function hidePopup() {
        shouldPopupContent.value = false;
    }

    return { hidePopup, popup, shouldPopupContent, togglePopup, popoverRef };
}
